package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IPrdInfoService;
import com.wondertek.poms.core.service.IProductService;
import com.wondertek.poms.core.service.ISellingPriceTagService;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.po.Product;
import com.wondertek.poms.dao.po.SellingPrice;
import com.wondertek.poms.dao.po.SellingPriceTag;
import com.wondertek.poms.dao.pojo.*;
import com.wondertek.poms.service.vo.ProductGroupVo;
import com.wondertek.poms.service.vo.SellingPriceTagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping(value = "/selling-price-tag")
public class SellingPriceTagController {

    @Autowired
    private ISellingPriceTagService sellingPriceTagService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IPrdInfoService prdInfoService;

    @GetMapping(value = "/list")
    @ResponseBody
    public ResultBean list(SellingPriceTagVo sellingPriceTagVo,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "CREATE_TIME") String sidx,
                           @RequestParam(defaultValue = "desc") String sord){
        SellingPriceTag sellingPriceTag=new SellingPriceTag();
        BeanUtils.copyProperties(sellingPriceTagVo,sellingPriceTag);
        Page<SellingPriceTagPojo> list=sellingPriceTagService.findAll(sellingPriceTag,page,rows,sord,sidx);
        return PageBean.ok(list.getTotalPages(),list.getTotalElements(),list.getContent());
    }

    @PostMapping(value = "/add")
    @ResponseBody
    @MethodLog(module = "标签售价新增",insertDB=true,opterate = 1)
    public ResultBean add(@RequestBody SellingPriceTagVo sellingPriceTagVo){
        List<String> messageList = ValidateFilter.getFilterMessage(sellingPriceTagVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }

        if(sellingPriceTagVo.getProductId()==null){
            String msg="计费点id不能为空！";
            return ResultBean.error(msg);
        }

        if(isRepeat(sellingPriceTagVo)){
            return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
        }


        int count=sellingPriceTagService.checkSellingPriceTagHaveDefault(sellingPriceTagVo.getPrdInfoId());
        if(count>0){
            if(StringUtil.isNullStr(sellingPriceTagVo.getMamRecomend())){
                return ResultBean.error("该商品包已存在空标签！");
            }
        }else{
            if(!StringUtil.isNullStr(sellingPriceTagVo.getMamRecomend())){
                return ResultBean.error("必须先配置该商品包的空标签！");
            }
        }
        String[] mamRecommendArr = sellingPriceTagVo.getMamRecomend().split(",|，");
        for(String temp:mamRecommendArr){
            SellingPriceTag sellingPriceTag=new SellingPriceTag();
            BeanUtils.copyProperties(sellingPriceTagVo,sellingPriceTag);
            sellingPriceTag.setMamRecomend(temp);
            SellingPriceTag.putTimeAndUser(sellingPriceTag);
            sellingPriceTagService.save(sellingPriceTag);
        }
        return ResultBean.ok();
    }

    @GetMapping(value = "/get-productIds")
    @ResponseBody
    public ResultBean getProductIds(){
        List<KeyValuePojo> result=new ArrayList<>();
        List<Product> list=productService.findAll();
        for(Product product:list){
            KeyValuePojo pojo=new KeyValuePojo();
            pojo.setKey(product.getProductID());
            pojo.setValue(product.getPrice());
            result.add(pojo);
        }
        return ResultBean.ok(result);
    }

    @GetMapping(value = "/get-prdInfos")
    @ResponseBody
    public ResultBean getPrdInfo(){
        List<PrdInfo> list=prdInfoService.findAll();
        List<KeyValuePojo> result=new ArrayList<>();
        for(PrdInfo prdInfo:list){
            KeyValuePojo pojo=new KeyValuePojo();
            pojo.setKey(prdInfo.getName());
            pojo.setValue(prdInfo.getPrdInfoId().toString());
            result.add(pojo);
        }
        return ResultBean.ok(result);
    }

    @PostMapping(value = "/import")
    @ResponseBody
    @MethodLog(module = "标签售价导入",insertDB=true,opterate = 6)
    public ResultBean importSellingPriceTag(MultipartFile file){
        StringBuffer msg = new StringBuffer("导入数据总数->");
        StringBuffer errMessage = new StringBuffer(".错误原因是->");
        AtomicInteger errNum = new AtomicInteger();// 全局错误数
        List<SellingPriceTagExcelPojo> list=new ArrayList<>();
        try{
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<SellingPriceTagExcelPojo> dataList=ei.getDataList(SellingPriceTagExcelPojo.class);
            if (CollectionUtil.isNotEmpty(dataList)) {
                msg.append(dataList.size() + ".错误数据数->");
                dataList.forEach(v -> importData(errMessage, errNum, v, list));
            } else {
                return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
            }

            if (CollectionUtil.isNotEmpty(list)){
                for(SellingPriceTagExcelPojo pojo:list){
                    String[] mamRecommendArr = pojo.getMamRecomend().split(",|，");
                    for(String mam:mamRecommendArr){
                        SellingPriceTag sellingPriceTag=new SellingPriceTag();
                        sellingPriceTag.setPrdInfoName(pojo.getPrdInfoName());
                        sellingPriceTag.setProductId(pojo.getProductId());
                        sellingPriceTag.setMamRecomend(mam);
                        SellingPriceTag.putTimeAndUser(sellingPriceTag);
                        PrdInfo temp=new PrdInfo();
                        temp.setName(pojo.getPrdInfoName());
                        PrdInfo prdInfo=prdInfoService.findOne(temp);
                        sellingPriceTag.setPrdInfoId(prdInfo.getPrdInfoId().toString());
                        Product productTemp=new Product();
                        productTemp.setProductID(pojo.getProductId().toString());
                        Product product=productService.findOne(productTemp);
                        sellingPriceTag.setPrice(product.getPrice());
                        sellingPriceTagService.save(sellingPriceTag);
                    }
                }

            }
            msg.append(errNum);
            msg.append(errMessage);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
        }
        if (errNum.get() > 0) {
            return ResultBean.error(msg.toString().replace("[", "").replace("]", "").replace("[]", "").replace("!", ""));
        }
        return ResultBean.ok();
    }


    public void importData(StringBuffer errMessage,AtomicInteger errNum,SellingPriceTagExcelPojo pojo,List<SellingPriceTagExcelPojo> list){
        if(pojo !=null){
            Boolean flag=true;
            List<String> messageList = ValidateFilter.getFilterMessage(pojo, Constants.VALIDATE_DEFAULT);
            flag = checkData(errMessage, errNum, pojo, flag, messageList);
            if (flag ) {
                list.add(pojo);
            }
        }
    }

    public Boolean checkData(StringBuffer errMessage, AtomicInteger errNum, SellingPriceTagExcelPojo pojo, Boolean flag, List<String> messageList){
        if (flag && !messageList.isEmpty()) {
            errNum.addAndGet(1);
            flag = false;
            errMessage.append("导入出错：" + messageList.toString() + ".  ");
        }
        if(flag && pojo.getProductId()==null){
            errNum.addAndGet(1);
            flag = false;
            errMessage.append("导入出错：标签：" + pojo.getMamRecomend() + " 对应的计费点必须为数字类型，不能为空.  ");
        }

        if(flag){
            SellingPriceTagVo sellingPriceTagVo=new SellingPriceTagVo();
            String[] mamRecommendArr = pojo.getMamRecomend().split(",|，");
            for(String mam:mamRecommendArr){
                sellingPriceTagVo.setMamRecomend(mam);
                if(isRepeat(sellingPriceTagVo)){
                    errNum.addAndGet(1);
                    flag = false;
                    errMessage.append("推荐标签：" + pojo.getMamRecomend() + "导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
                }
            }
        }

        if(flag){
            PrdInfo temp=new PrdInfo();
            temp.setName(pojo.getPrdInfoName());
            PrdInfo prdInfo=prdInfoService.findOne(temp);
            if(prdInfo==null){
                errNum.addAndGet(1);
                flag = false;
                errMessage.append("推荐标签：" + pojo.getMamRecomend() + "导入出错：商品包："+pojo.getPrdInfoName()+" 不存在.  ");
            }else {
                int count=sellingPriceTagService.checkSellingPriceTagHaveDefault(prdInfo.getPrdInfoId().toString());
                if(count>0){
                    if(StringUtil.isNullStr(pojo.getMamRecomend())){
                        errNum.addAndGet(1);
                        flag = false;
                        errMessage.append("推荐标签：" + pojo.getMamRecomend() + "导入出错：商品包："+pojo.getPrdInfoName()+" 已存在空标签.  ");
                    }
                }else{
                    if(!StringUtil.isNullStr(pojo.getMamRecomend())){
                        errNum.addAndGet(1);
                        flag = false;
                        errMessage.append("推荐标签：" + pojo.getMamRecomend() + "导入出错：必须先配置商品包："+pojo.getPrdInfoName()+" 的空标签.  ");
                    }
                }
            }
        }

        if(flag){
            Product productTemp=new Product();
            productTemp.setProductID(pojo.getProductId().toString());
            Product product=productService.findOne(productTemp);
            if(product==null){
                errNum.addAndGet(1);
                flag = false;
                errMessage.append("推荐标签：" + pojo.getMamRecomend() + "导入出错：计费点："+pojo.getProductId()+" 不存在.  ");
            }
        }
        if(flag){

        }
        return flag;
    }

    public Boolean isRepeat(SellingPriceTagVo sellingPriceTagVo){
        SellingPriceTag temp=new SellingPriceTag();
        temp.setMamRecomend(sellingPriceTagVo.getMamRecomend());
        temp.setPrdInfoId(sellingPriceTagVo.getPrdInfoId());
        Optional<SellingPriceTag> opt=sellingPriceTagService.findOne(Example.of(temp));
        if(opt.isPresent()){
            SellingPriceTag sellingPriceTag=opt.get();
            if(sellingPriceTagVo.getId()!=null && sellingPriceTagVo.getId()!=sellingPriceTag.getId()){
                return true;
            }
            if(sellingPriceTagVo.getId()==null){
                return true;
            }
        }
        return false;
    }
}
